package com.baizhi;

import com.baizhi.dao.AdminDao;
import com.baizhi.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class ShiroTests2 {
    private Logger logger = LoggerFactory.getLogger(ShiroTests2.class);

    @Test
    public void test2(){
        String username = "sw";
        String password = "123456";

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        IniSecurityManagerFactory securityManagerFactory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = securityManagerFactory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
            logger.info("登录成功!!!!!");
            if(subject.hasRole("sadmin")){
                logger.info("具有超级管理员的权限");
            }
            if(subject.hasRole("admin")){
                logger.info("具有普通管理员的权限");
            }
            if(subject.isPermitted("banner:add")){
                logger.info("可以调用轮播图的添加方法");
            }
            if(subject.isPermitted("banner:update")){
                logger.info("可以调用轮播图的修改方法");
            }
            if(subject.isPermitted("article:*")){
                logger.info("可以调用文章的所有方法");
            }
            if(subject.isPermitted("banner:*")){
                logger.info("可以调用轮播图的所有方法");
            }

        } catch (IncorrectCredentialsException e) {
            logger.info("密码错误!!!");
        } catch (UnknownAccountException s) {
            logger.info("账号错误!!!");
        }
        //在项目的任意位置 可以通过isAuthenticated方法 查看当前用户是否登录成功
        boolean authenticated = subject.isAuthenticated();
        logger.info(authenticated+"");
    }
}
